<template>
  <view class="index">
    <!-- 顶部banner -->
    <Inform v-if="globalData.hasLogin" />
    <!-- 轮播图 -->
    <Slideshow v-if="globalData.hasLogin" />

    <view>
      <!-- 如果未登录，显示提示信息 -->
      <view v-if="!globalData.hasLogin" class="prompt">
        您尚未登录，请点击按钮进行授权。
        <button @click="getinfo">获取信息</button>
        <button @click="toggleModal(true)">点击这里登录并授权</button>
      </view>
      <!-- 如果已登录，显示欢迎信息 -->
      <!-- <view v-else class="welcome">
        欢迎回来，{{ globalData.userInfo && globalData.userInfo.nickName }}!
      </view> -->

      <!-- 自定义模态对话框 -->
      <view
        :class="['modal-overlay', { 'is-active': showModal }]"
        @tap="toggleModal(false)"
      >
        <view class="modal-content" @tap.stop>
          <text class="modal-title">用户授权</text>
          <text class="modal-message">请授权以继续使用本应用</text>
          <button class="modal-button" @click="handleLogin">授权</button>
          <button class="modal-button cancel" @click="toggleModal(false)">
            取消
          </button>
        </view>
      </view>
    </view>

    <view class="content" v-if="globalData.hasLogin">
      <Presentation />

      <!-- 活动信息 -->
      <view class="rule">
        <view class="p"
          >投票开始：{{
            dayjs(activityMsgs.startTime).format("YYYY年MM月DD日 HH:mm:ss")
          }}</view
        >
        <view class="p"
          >投票结束：{{
            dayjs(activityMsgs.endTime).format("YYYY年MM月DD日 HH:mm:ss")
          }}</view
        >
        <view class="p">{{ activityMsgs.rule }}</view>
      </view>

      <!-- 排行切换 -->
      <view class="rank">
        <view
          :class="[active === item ? 'active p' : 'p']"
          v-for="item in select"
          :key="item"
          @click="switchRank(item)"
        >
          {{ item }}
        </view>
      </view>

      <!-- 职位 -->
      <Position @onSelectPosition="fetchPositionData" />
      <!-- 搜索 -->
      <view class="search">
        <input placeholder="搜索" v-model="searchval" />
        <button @click="search">搜索</button>
      </view>
      <view class="searchval" v-if="searchval"
        >搜索关键词 “{{ searchval }}”
        <text @click="unsearch">取消搜索</text></view
      >

      <!-- 用户列表 -->
      <view class="list">
        <view class="list-item" v-for="item in userInfo" :key="item._id">
          <image
            style="width: 100%"
            mode="widthFix"
            :src="item.avtor"
            alt=""
            @click="goDetail(item._id)"
          />
          <view class="h3">{{ item.name }}</view>
          <view class="named">{{ item.laber }}</view>
          <view class="vote">{{ item.vote }}票</view>
          <button @click="change(item._id, item.isCheck)">
            {{ item.isCheck ? "取消" : "选择" }}
          </button>
        </view>
      </view>
    </view>

    <!-- 底部 -->
    <view class="footer" v-if="candidate_ids.length > 0 && globalData.hasLogin">
      <view>
        已选择
        <text class="yellow">{{
          userInfo.filter((item) => item.isCheck).length
        }}</text>
        选手 &nbsp;
        <text @click="clear">取消</text>
      </view>
      <button @click="vote">投票</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import dayjs from "dayjs";
import Inform from "../components/Inform/Inform.vue";
import Slideshow from "../components/Slideshow/Slideshow.vue";
import Presentation from "../components/Presentation/Presentation.vue";
import { ref, reactive } from "vue";
import {
  onLoad,
  onShareAppMessage,
  onReachBottom,
  onShow,
} from "@dcloudio/uni-app";
import Position from "../components/Position/Position.vue";

const activityMsgs = ref([]);
const userInfo = ref([]);
const select = ["排行", "最热", "最新"];
const active = ref(select[0]); // 默认选中第一个
const candidate_ids = ref([]);
const total = ref(0);
const nowPage = ref(1);
const onloding = ref(false);
const searchval = ref(""); // 搜索关键词
const p_id = ref(""); // 搜索职位id

// 定义全局数据
const globalData = reactive({
  openid: null,
  userInfo: null,
  hasLogin: false,
});

// 控制模态框显示状态
const showModal = ref(false);

const getinfo = () => {
  wx.getUserProfile({
    desc: "用于完善会员资料", // 这里需要填写你获取用户信息的用途，将展示在授权弹窗中
    success: (res) => {
      console.log("用户同意授权，返回的信息：", res);
      // 在这里可以对用户信息进行处理，比如保存到本地或上传服务器
    },
    fail: (res) => {
      console.log("用户拒绝授权");
      // 用户拒绝了授权，可以根据业务逻辑决定下一步操作
    },
  });
};

// 页面显示时再次检查登录状态（可选）
onShow(async () => {
  if (!globalData.hasLogin) {
    try {
      const res = await uni.getStorage({ key: "openid" });
      globalData.openid = res.data;
      globalData.hasLogin = true;
    } catch (error) {
      // 保持未登录状态
    }
  }
});

// 切换模态框显示状态
function toggleModal(state: boolean) {
  showModal.value = state;
}

// 处理登录的方法
async function handleLogin() {
  try {
    // 调用登录接口
    const res = await uni.login();
    const code = res.code;
    // 发送请求到后端获取openid
    const openidRes = await uni.request({
      url: "http://1.92.114.25:6624/login",
      method: "POST",
      data: { code },
    });

    // 获取openid成功
    if (openidRes.statusCode === 200) {
      uni.getUserInfo({
        success: (res) => {
          console.log(res, "用户信息：：");
          uni.request({
            url: "http://1.92.114.25:6624/saveUserInfo",
            method: "POST",
            data: { res },
            success: (success) => {
              console.log(success, "授权成功");
            },
          });
        },
        fail: (err) => {
          console.log(err, "获取用户信息失败");
        },
      });
      const openid = openidRes.data.openid;
      // 将openid存储到全局数据中
      globalData.openid = openid;
      // 将登录状态设置为已登录
      globalData.hasLogin = true;
      // 将openid存储到本地
      uni.setStorage({ key: "openid", data: openid });
      //关闭模态框
      toggleModal(false);
    } else {
      console.error("获取openid失败", openidRes);
    }
    //关闭模态框
    toggleModal(false);
  } catch (error) {
    console.error("登录失败", error);
  }
}

//跳转详情
const goDetail = (id: number) => {
  console.log("detail-id", id);

  uni.navigateTo({
    url: `/pages/detail/detail?id=${id}`,
  });
};

// 分享功能
onShareAppMessage(() => {
  return { title: "投票", path: "/pages/index/index" };
});

// 获取活动信息
uni.request({
  url: "http://1.92.114.25:6624/getactives",
  method: "GET",
  success: (res: any) => {
    activityMsgs.value = res.data.activityMsgs[0];
  },
  fail: (err) => {
    console.error(err);
  },
});

// 搜索标志位
let isSearching = ref(false);

const fetchData = (reachBottom = false) => {
  if (onloding.value || (!isSearching.value && searchval.value)) return; // 如果正在加载或处于搜索状态但有新的搜索值，则不执行
  onloding.value = true;

  uni.request({
    url: "http://1.92.114.25:6624/getuser",
    method: "GET",
    data: {
      nowPage: nowPage.value,
      pageSize: 3,
      ...(isSearching.value ? { searchcontent: searchval.value } : {}),
    },
    success: (res: any) => {
      total.value = res.data.userstotal;
      // 如果不是触底加载（即首次加载或刷新），则覆盖用户信息；否则追加新用户信息
      userInfo.value = reachBottom
        ? [...userInfo.value, ...res.data.users]
        : res.data.users;
      nowPage.value++;
    },
    fail: (err) => {
      console.error(err);
    },
    complete: () => {
      onloding.value = false;
    },
  });
};

// 搜索
const search = () => {
  isSearching.value = true;
  nowPage.value = 1;
  userInfo.value = []; // 清空之前的数据
  fetchData();
};

// 获取用户列表
const getUserInfo = () => {
  if (!isSearching.value) {
    fetchData();
  }
};

// 触底加载
onReachBottom(() => {
  // 检查是否有更多数据可加载，不依赖 isSearching 的状态
  if (nowPage.value <= Math.ceil(total.value / 3)) {
    fetchData(true); // 调用 fetchData 并传递参数表示这是触底加载
  }
});

// 取消搜索
const unsearch = () => {
  searchval.value = "";
  p_id.value = "";
  fetchRankData(active.value);
};

// 获取排行数据
const fetchRankData = async (type) => {
  let url = "";
  switch (type) {
    case "最热":
      url = "http://1.92.114.25:6624/users/getHot";
      break;
    case "最新":
      url = "http://1.92.114.25:6624/users/getNew";
      break;
    case "排行":
      url = "http://1.92.114.25:6624/users/getHot";
      break;
    default:
      return;
  }
  try {
    const res = await uni.request({
      url,
      method: "GET",
      data: { page: nowPage.value },
    });
    console.log(res);
    if (res.statusCode === 200 && res.data.code === 200) {
      userInfo.value = res.data.data; // 更新用户数据
    }
  } catch (err) {
    console.error("获取排行数据失败", err);
  }
};

// 切换排行
const switchRank = (type) => {
  if (active.value !== type) {
    active.value = type; // 更新当前选中的类型
    nowPage.value = 1; // 重置分页
    fetchRankData(type); // 获取新数据
  }
};

// 获取选中职位的数据
const fetchPositionData = (_id: string) => {
  p_id.value = _id;
  uni.request({
    url: "http://1.92.114.25:6624/getuser",
    method: "GET",
    data: { positionid: p_id.value, searchcontent: searchval.value },
    success: (res: any) => {
      userInfo.value = res.data.users; // 更新用户数据
    },
    fail: (err) => {
      console.error(err);
    },
  });
};

// 页面加载时获取用户列表
onLoad(() => getUserInfo());

// 投票操作
const vote = () => {
  uni.request({
    url: "http://1.92.114.25:6624/udvote",
    method: "POST",
    data: {
      voter_id: globalData.openid, // 替换为实际的用户ID
      candidate_ids: candidate_ids.value,
      vtime: Date.now(),
    },
    success: (res) => {
      if (res.data.code === 200) {
        candidate_ids.value = [];
        userInfo.value.forEach((item) => (item.isCheck = false));
        uni.showToast({ title: "投票成功", icon: "success" });
      } else {
        candidate_ids.value = [];
        userInfo.value.forEach((item) => (item.isCheck = false));
        uni.showToast({ title: res.data.message, icon: "none" });
      }
    },
    fail: (err) => {
      console.error(err);
    },
  });
};

// 改变选中状态
const change = (id: string, isCheck: boolean) => {
  if (candidate_ids.value.length >= 2 && !isCheck) {
    uni.showToast({ title: "最多只能选择两位选手", icon: "none" });
    return;
  }
  const index = userInfo.value.findIndex((item) => item._id === id);
  userInfo.value[index].isCheck = !isCheck;
  if (isCheck) {
    candidate_ids.value = candidate_ids.value.filter((cid) => cid !== id);
  } else {
    candidate_ids.value.push(id);
  }
  console.log(candidate_ids.value, "candidate_ids");
};

// 清除所有选中
const clear = () => {
  candidate_ids.value = [];
  userInfo.value.forEach((item) => (item.isCheck = false));
};
</script>

<style lang="scss" scoped>
.index {
  width: 100vw;
  min-height: 100vh;
  background-color: #211c25;

  .content {
    width: 85%;
    margin: 0 auto;
    padding: 20rpx 0;
    padding-bottom: 50px;

    // 活动规则
    .rule {
      margin: 20px auto;
      width: 100%;
      height: 100%;
      border: 3px solid #fdcb77;
      border-radius: 10px;
      background-color: #332f38;

      .p {
        margin: 25px;
        color: #e0e0e0;
      }
    }

    // 排行
    .rank {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      border: 3px solid #fdcb77;

      .p {
        flex: 1;
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: #e0e0e0;
      }

      .active {
        color: #7b492b;
        background-image: linear-gradient(to bottom, #f7d695, #ceab7b);
      }
    }

    .search {
      margin-top: 20px;
      border: 3px solid #fdcb77;
      width: 100%;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;

      input {
        width: 73%;
        height: 45px;
        border: none;
        padding-left: 20px;
        color: #ffffff;
        background-color: #211c25;
      }

      button {
        border-radius: 0px;
        width: 27%;
        height: 49px;
        background-image: linear-gradient(to bottom, #f7d695, #ceab7b);
        color: #7b492b;
        font-weight: bold;
        border: none;
        line-height: 49px;
      }
    }

    // 关键字提示
    .searchval {
      text-align: center;
      color: #bbb8b5;
      line-height: 50px;
      height: 50px;
      width: 100%;
    }

    //选手列表
    .list {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;

      .list-item {
        margin-top: 10px;
        border: 3px solid #f8c588;
        box-sizing: border-box;
        width: 48%;
        height: 100%;

        img {
          
        }

        .h3 {
          color: #ffffff;
        }

        .named {
          font-size: 14px;
          margin: 5px;
          color: #bbb8b5;
        }

        .vote {
          color: #fff;
          background-color: #504d54;
        }

        button {
          width: 100%;
          height: 40px;
          background-image: linear-gradient(to bottom, #f7d695, #ceab7b);
          color: #7b492b;
          font-weight: bold;
          border-radius: 0;
        }
      }
    }
  }

  .footer {
    border-radius: 5px 5px 0 0;
    background-color: #504d54;
    width: 100%;
    height: 50px;
    position: fixed;
    bottom: 0;
    line-height: 50px;
    display: flex;
    justify-content: space-around;
    color: #bbb8b5;
    align-items: center;

    button {
      width: 25%;
      margin: 0;
      height: 40px;
      border-radius: 25px;
      border: none;
      line-height: 40px;
      background-image: linear-gradient(to bottom, #f7d695, #ceab7b);
      color: #7b492b;
    }
  }
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.prompt,
.welcome {
  text-align: center;
}

/* 模态框背景 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: none;
  justify-content: center;
  align-items: center;
}

.modal-overlay.is-active {
  display: flex;
}

/* 模态框内容 */
.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  width: 80%;
  max-width: 300px;
  text-align: center;
}

.modal-title {
  font-size: 18px;
  margin-bottom: 10px;
}

.modal-message {
  margin-bottom: 20px;
}

.modal-button {
  margin: 5px 0;
  width: 80%;
}

.cancel {
  background-color: #ccc;
  color: white;
}
</style>